<?php

namespace fast;

use think\Cache;
use fast\Http;

class WechatMini
{
    public $appid;
	public $sessionKey;
	public $token;
	private $providers = [
        'wechat'  => 'Wechat',
    ];
	/**
	 * 构造函数
	 * @param $sessionKey string 用户在小程序登录后获取的会话密钥
	 * @param $appid string 小程序的appid
	 */
	public function __construct()
	{	
		$config = get_addon_config('third');

		$options = array_intersect_key($config, $this->providers);
        $options = array_merge([], is_array($options) ? $options : []);

        $config2 = $options['wechat'];
		$this->appid = 'wx80d5e749a136ffb3';
		$this->secret = '41505ba0db73f75b1bfb5a012862b419';
		$this->token = Cache::get('wecahtmini_token');
	
		if (empty($this->token)) {
			$this->getToken();
		}
	}



	public function getToken(){
		$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->secret;
		
		$data = Http::get($url);

		$data = json_decode($data,true);
		if (isset($data['access_token'])) {
			$this->token = $data['access_token'];
			Cache::set('wecahtmini_token',$data['access_token'],7200);
		}

	}

	public function send($openid,$user){
		$url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$this->token;
		$data['access_token'] = $this->token;
		$data['touser'] = $openid;
		$data['template_id'] = 'M6Oe2VV7pXjhN1amQ6P_SOCINfpMUOhwA9_LrZaPanI';
		$data['data']['name1']['value'] = $user['name'];
		$data['data']['date3']['value'] = $user['day'];
		$data['data']['number20']['value'] = $user['num'];
		$data = json_encode($data);
		$data = Http::post($url,$data);

	}


	public function getuserphonenumber($code){
		$url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$this->token;
		
		$data['code'] = $code;
		$data = json_encode($data);

	
		$ret = Http::post($url,$data);
		$ret = html_entity_decode($ret);
		$ret = json_decode($ret,true);
		return $ret;
	}
	public function getretailinfo($openid){
		$url = 'https://api.weixin.qq.com/wxa/business/getretailinfo?access_token='.$this->token;
		
		$data['openid'] = $openid;
		$data = json_encode($data);

	
		$ret = Http::post($url,$data);
		$ret = html_entity_decode($ret);
		$ret = json_decode($ret,true);
		return $ret;
	}


}

